package com.lxmes.base.service.impl;

import java.util.Date;
import java.util.List;

import com.lxmes.base.domain.*;
import com.lxmes.base.mapper.*;
import com.lxmes.common.core.domain.entity.SysDictData;
import com.lxmes.common.core.domain.entity.SysRole;
import com.lxmes.common.core.domain.entity.SysUser;
import com.lxmes.common.core.domain.model.LoginUser;
import com.lxmes.common.exception.ServiceException;
import com.lxmes.common.utils.DateUtils;
import com.lxmes.common.utils.SecurityUtils;
import com.lxmes.common.utils.StringUtils;
import com.lxmes.common.utils.bean.BeanValidators;
import com.lxmes.system.mapper.SysDictDataMapper;
import com.lxmes.system.service.ISysConfigService;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lxmes.base.service.IJcIteminfoService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.Validator;

/**
 * 物料信息Service业务层处理
 *
 * @author ruoyi
 * @date 2022-06-11
 */
@Service
public class JcIteminfoServiceImpl implements IJcIteminfoService
{
    @Resource
    private JcIteminfoMapper jcIteminfoMapper;

    @Autowired
    private ISysConfigService configService;

    //大类
    @Resource
    private JcIteminfoClassMapper iteminfoClassMapper;

    //供应商
    @Resource
    private NcSupplierMapper supplierMapper;

    //字典校验单位
    @Resource
    private SysDictDataMapper dictDataMapper;
    @Resource
    private JcIteminfoGzMapper iteminfoGzMapper;
    @Resource
    private JcItembzinfoMapper itembzinfoMapper;

    @Autowired
    protected Validator validator;

    private static final Logger log = LoggerFactory.getLogger(JcIteminfoServiceImpl.class);

    /**
     * 查询物料信息
     *
     * @param id 物料信息主键
     * @return 物料信息
     */
    @Override
    public JcIteminfo selectJcIteminfoById(Long id)
    {
        return jcIteminfoMapper.selectJcIteminfoById(id);
    }
    //根据物料条码获取物料
    @Override
    public JcIteminfo selectJcIteminfoByTmh(String tmh) {
        return jcIteminfoMapper.selectJcIteminfoByTmh(tmh);
    }

    /**
     * 查询物料信息列表
     *
     * @param jcIteminfo 物料信息
     * @return 物料信息
     */
    @Override
    public List<JcIteminfo> selectJcIteminfoList(JcIteminfo jcIteminfo)
    {
        jcIteminfo.setFactoryCode(SecurityUtils.getFactoryCode());
        List<JcIteminfo> jcIteminfoList = jcIteminfoMapper.selectJcIteminfoList(jcIteminfo);
        /*Long roleId = SecurityUtils.getLoginUser().getUser().getRoleId();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysRole> roleList = user.getRoles();
        boolean present = roleList.stream().filter(m -> m.getRoleId()==100).findAny().isPresent();
        if(present){
            for (JcIteminfo iteminfo : jcIteminfoList) {
                iteminfo.setSupplyName(null);
                iteminfo.setSupplyId(null);
                iteminfo.setPrice(null);
            }
        }*/
        return jcIteminfoList;
    }

    @Override
    public List<JcIteminfo> selecIteminfoByIds(Long[] ids) {
        return jcIteminfoMapper.selecIteminfoByIds(ids);
    }


    @Override
    public JcIteminfo selectJcIteminfo(JcIteminfo jcIteminfo) {
        return jcIteminfoMapper.selectJcIteminfo(jcIteminfo);
    }

    /**
     * 新增物料信息
     *
     * @param jcIteminfo 物料信息
     * @return 结果
     */
    @Override
    public int insertJcIteminfo(JcIteminfo jcIteminfo)
    {
        jcIteminfo.setFactoryCode(SecurityUtils.getFactoryCode());
        jcIteminfo.setFactoryName(SecurityUtils.getFactoryName());
        jcIteminfo.setCreateTime(DateUtils.getNowDate());
        //大类
        JcIteminfoClass jcIteminfoClass = iteminfoClassMapper.selectJcIteminfoClassByCode(jcIteminfo.getClassId());
        if(jcIteminfoClass!=null){
            jcIteminfo.setClassName(jcIteminfoClass.getClassName());
        }

        //供应商
        NcSupplier supplier = supplierMapper.selectNcSupplierById(jcIteminfo.getSupplyId());
        if(supplier!=null){
            jcIteminfo.setSupplyName(supplier.getSupplierName());
        }
        if(StringUtils.isEmpty(jcIteminfo.getTmh())){
            jcIteminfo.setTmh(jcIteminfo.getItemId());
        }
        return jcIteminfoMapper.insertJcIteminfo(jcIteminfo);
    }

    /**
     * 修改物料信息
     *
     * @param jcIteminfo 物料信息
     * @return 结果
     */
    @Override
    public int updateJcIteminfo(JcIteminfo jcIteminfo)
    {
        jcIteminfo.setUpdateTime(DateUtils.getNowDate());
        jcIteminfo.setItemId(jcIteminfo.getItemCode());
        //大类
        JcIteminfoClass jcIteminfoClass = iteminfoClassMapper.selectJcIteminfoClassByCode(jcIteminfo.getClassId());
        if(jcIteminfoClass!=null){
            jcIteminfo.setClassName(jcIteminfoClass.getClassName());
        }

        //供应商
       /* NcSupplier supplier = supplierMapper.selectNcSupplierById(jcIteminfo.getSupplyId());
        if(supplier!=null){
            jcIteminfo.setSupplyName(supplier.getSupplierName());
        }*/
        if(StringUtils.isEmpty(jcIteminfo.getTmh())){
            jcIteminfo.setTmh(jcIteminfo.getItemId());
        }
        return jcIteminfoMapper.updateJcIteminfo(jcIteminfo);
    }

    /**
     * 批量删除物料信息
     *
     * @param ids 需要删除的物料信息主键
     * @return 结果
     */
    @Override
    public int deleteJcIteminfoByIds(Long[] ids)
    {
        for (int i = 0; i <ids.length ; i++) {
            //同步删除基础物料表
            JcIteminfo jc = jcIteminfoMapper.selectJcIteminfoById(ids[i]);
            if(jc==null){
                continue;
            }
            if(StringUtils.isNotEmpty(jc.getItemIdentifyCode())){
             /*   JcItembzinfo bz = itembzinfoMapper.selectJcItembzinfoByItemIdentifyCode(jc.getItemIdentifyCode());
                bz.setScFlag("0");
                itembzinfoMapper.updateJcItembzinfo(bz);*/
                JcIteminfoGz gz = iteminfoGzMapper.selectJcIteminfoGzByItemIdentifyCode(jc.getItemIdentifyCode());
                if(gz!=null){
                    gz.setScFlag("0");
                    iteminfoGzMapper.updateJcIteminfoGz(gz);
                }
                jcIteminfoMapper.deleteJcIteminfoByItemIdentifyCode(jc.getItemIdentifyCode());
            }else {
                jcIteminfoMapper.deleteJcIteminfoById(ids[i]);
            }
        }
        return 1;
    }

    @Override
    public int delAllItemInfo() {
        return jcIteminfoMapper.delAllItemInfo();
    }

    /**
     * 删除物料信息信息
     *
     * @param id 物料信息主键
     * @return 结果
     */
    @Override
    public int deleteJcIteminfoById(Long id)
    {
        return jcIteminfoMapper.deleteJcIteminfoById(id);
    }

    @Override
    @Transactional
    public String imporIteminfo(List<JcIteminfo> iteminfoList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(iteminfoList) || iteminfoList.size() == 0)
        {
            throw new ServiceException("导入物料数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (JcIteminfo iteminfo : iteminfoList)
        {
            try
            {

                //判断几个关键字段不能为空否则直接跳出循环
                if(StringUtils.isEmpty(iteminfo.getItemCode())){
                    throw new ServiceException("物料编号不能为空,请仔细检查数据!!");
                }
                if(StringUtils.isEmpty(iteminfo.getItemName())){
                    throw new ServiceException("物料名称不能为空,请仔细检查数据!!");
                }
               /* if(iteminfo.getClassId()==null){
                    throw new ServiceException("物料大类不能为空,请仔细检查数据!!");
                }
                if(iteminfo.getSupplyId()==null){
                    throw new ServiceException("供应商编号不能为空,请仔细检查数据!!");
                }*/
                //校验单位
                /*if(StringUtils.isNotEmpty(iteminfo.getUnit())){
                    SysDictData dictData = new SysDictData();
                    dictData.setDictType("jc_iteminfo_unit");
                    dictData.setDictLabel(iteminfo.getUnit());
                    List<SysDictData> sysDictDataList = dictDataMapper.selectDictDataList(dictData);
                    if(StringUtils.isNull(sysDictDataList) || sysDictDataList.size() == 0){
                        throw  new ServiceException("单位与字典维护的不一致，请检查!!");
                    }
                }*/

                //验证大类是否存在
                //大类
              /*  JcIteminfoClass jcIteminfoClass = iteminfoClassMapper.selectJcIteminfoClassByCode(iteminfo.getClassId());
                if(jcIteminfoClass==null){
                    throw new ServiceException("物料分类不能为空!");
                }
                iteminfo.setClassName(jcIteminfoClass.getClassName());*/
                /*//验证供应商是否存在
                JcSupplier supplier = new JcSupplier();
                supplier.setId(iteminfo.getSupplyId());
                List<JcSupplier> jcSupplierList = supplierMapper.selectJcSupplierList(supplier);

                if(StringUtils.isNull(jcSupplierList)){
                    throw new ServiceException(iteminfo.getItemCode()+"没有维护供应商!");
                }*/
                // 验证是否存在这个物料
                JcIteminfo jcIteminfoSearch = new JcIteminfo();
                jcIteminfoSearch.setItemId(iteminfo.getItemId());
                JcIteminfo u = jcIteminfoMapper.selectJcIteminfo(jcIteminfoSearch);
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, iteminfo);
                    iteminfo.setCreateBy(operName);
                    iteminfo.setCreateTime(new Date());
                    iteminfo.setUpdateBy(operName);
                    iteminfo.setDeptId(SecurityUtils.getDeptId());
                    iteminfo.setFactoryCode(SecurityUtils.getFactoryCode());
                    iteminfo.setFactoryName(SecurityUtils.getFactoryName());
                    jcIteminfoMapper.insertJcIteminfo(iteminfo);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + iteminfo.getItemName() + " 导入成功");
                }
                else
                {
                    BeanValidators.validateWithException(validator, iteminfo);
                    iteminfo.setUpdateBy(operName);
                    jcIteminfoMapper.updateJcIteminfo(iteminfo);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、数据 " + iteminfo.getItemName()+ " 更新成功");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + iteminfo.getItemName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<JcIteminfo> mobilejcIteminforecordList(JcIteminfo jcIteminfo) {
        List<JcIteminfo> jcIteminfoList = jcIteminfoMapper.mobileWarehouserecordList(jcIteminfo);
        List<SysRole> roleList = SecurityUtils.getLoginUser().getUser().getRoles();

        boolean present = roleList.stream().filter(m -> m.getRoleId()==100).findAny().isPresent();
        if(present){
            for (JcIteminfo iteminfo : jcIteminfoList) {
                iteminfo.setPrice(null);
                iteminfo.setSupplyId(null);
                iteminfo.setSupplyName(null);
            }
        }
        return jcIteminfoList;
    }

    @Override
    public List<JcIteminfo> getItemAllCode() {
        return jcIteminfoMapper.getItemAllCode();
    }

    private int updateJcIteminfoByCode(JcIteminfo iteminfo) {
        iteminfo.setUpdateTime(DateUtils.getNowDate());
        return jcIteminfoMapper.updateJcIteminfoByCode(iteminfo);
    }

}
